<?php
namespace app\api\controller\factory;

use think\Request;
use app\common\model\factory\User as UserModel;
use app\common\model\factory\Factory as FactoryModel;
use app\common\model\power\Rolepower;
use app\api\controller\Pub;
use app\api\controller\Base;

class Factory extends Base
{
    public function initialize()
    {
        parent::initialize();
        // $this->is_login();
        Rolepower::powerguard('301001'); // 工厂员工管理权限
    }

    // private function is_login()
    // {
    //     $data = UserModel::is_sessionlogin();
    //     if (!$data['code']) {
    //         $data['options'] = 'relogin';
    //         json($data)->send();
    //         exit;
    //     }
    // }

    // 工厂员工列表
    public function userList(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);
        $keyword = $request->get('keyword', '');

        $pub = new Pub();
        $userId = $pub->userid();
        $factoryId = UserModel::getFactoryId($userId);

        if (!$factoryId) {
            return json(['code' => 0, 'msg' => '未绑定工厂']);
        }

        $factoryModel = new FactoryModel();
        $list = $factoryModel->getStaffList($factoryId, $keyword, $page, $pageSize);

        return json(['code' => 1, 'msg' => 'success', 'data' => $list]);
    }

    // 添加员工
    public function userAdd(Request $request)
    {
        $pub = new Pub();
        $userId = $pub->userid();
        $factoryId = UserModel::getFactoryId($userId);

        if (!$factoryId) {
            return json(['code' => 0, 'msg' => '未绑定工厂']);
        }

        $data = $request->post();
        if (empty($data['Iphone']) || empty($data['Name']) || empty($data['sex'])) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }

        $factoryModel = new FactoryModel();
        $result = $factoryModel->addStaff($factoryId, $data);

        return $result 
            ? json(['code' => 1, 'msg' => '添加成功']) 
            : json(['code' => 0, 'msg' => '添加失败']);
    }

    // 员工信息修改
    public function userEdit(Request $request)
    {
        $data = $request->post();
        if (empty($data['UserId']) || empty($data['Name']) || empty($data['Iphone']) || empty($data['sex'])) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }

        $result = UserModel::updateInfo($data['UserId'], $data);

        return $result 
            ? json(['code' => 1, 'msg' => '修改成功']) 
            : json(['code' => 0, 'msg' => '用户不存在或修改失败']);
    }

    // 删除员工
    public function userDel(Request $request)
    {
        $userId = $request->post('UserId');
        if (empty($userId)) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }

        $result = UserModel::deleteUser($userId);

        return $result 
            ? json(['code' => 1, 'msg' => '删除成功']) 
            : json(['code' => 0, 'msg' => '删除失败']);
    }
}